package com.qs.services;

import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;

import com.qs.dao.UserDAO;
import com.qs.entities.Channel;
import com.qs.entities.User;
import com.qs.exceptions.ServiceException;
import com.qs.utils.EncryptionUtils;
import com.qs.utils.HttpStatusStrings;

public class UserService {
	
	private UserDAO	userDao;
	
	public User fetchUser(String email,String password) throws ServiceException{
		try{
			List<User> listUsers =  userDao.findByEmail(email);
			
			if(listUsers == null || listUsers.size()<1)
				throw new ServiceException("User not found.");
			
			User user = listUsers.get(0);
			
			if(EncryptionUtils.checkPassword(password, user.password)){
				return user;
			}
			else{
				throw new ServiceException(HttpStatusStrings.INVALID_CREDENTIALS);
			}
		}
		catch(Exception exc){
			throw new ServiceException(exc.getMessage(),exc);
		}		
	}
	
	public User createUser(	String firstName,String lastName, String screenName, 
							String email, String password,String address, String phone, List<String> channelIds) throws ServiceException{
		
		try{
			User user = new User();
			user.userId		= UUID.randomUUID().toString();
			user.firstName 	= firstName;
			user.lastName	= lastName;
			user.screenName	= screenName;
			user.email		= email;
			user.password	= EncryptionUtils.encryptPassword( password );
			user.address	= address;
			user.phone		= phone;
			user.channels 	= new HashSet<Channel>();
			
			if(channelIds!=null && channelIds.size()>0){
				for(String id:channelIds)
					user.channels.add(new Channel(Integer.parseInt(id)));
			}
			
			userDao.save(user);
			return user;
		}
		catch(Exception exc){
			throw new ServiceException(exc.getMessage(),exc);
		}
	}
	
	
	public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}

	public void updateUser(User user)throws ServiceException  {
		try{
			userDao.attachDirty(user);
		}
		catch(Exception exc){
			throw new ServiceException(exc.getMessage(),exc);
		}
		
	}
	
}
